const { Sequelize, DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, 'src', '.env.development') });

// 数据库配置
const sequelize = new Sequelize({
  dialect: 'mysql',
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  username: process.env.DB_USERNAME || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'easy-front-nest-db',
  logging: console.log,
});

// 定义模型
const TUser = sequelize.define('t_user', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  nick: {
    type: DataTypes.STRING(50),
    allowNull: false,
  },
  avatar: {
    type: DataTypes.STRING(255),
    allowNull: true,
  },
  tag: {
    type: DataTypes.STRING(50),
    allowNull: true,
  },
  note: {
    type: DataTypes.STRING(255),
    allowNull: true,
  },
  role_type: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 1,
  },
  user_status: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 1,
  },
  created_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
  },
  updated_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
  },
}, {
  tableName: 't_user',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
});

const TUserLogin = sequelize.define('t_user_login', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  login_type: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  login_client: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  account_id: {
    type: DataTypes.STRING(50),
    allowNull: false,
  },
  account_pwd: {
    type: DataTypes.STRING(255),
    allowNull: false,
  },
  pwd_salt: {
    type: DataTypes.STRING(50),
    allowNull: true,
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  created_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
  },
  updated_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
  },
}, {
  tableName: 't_user_login',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
});

// 创建admin账号的函数
async function createAdminAccount() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');

    // 检查admin账号是否已存在
    const existingLogin = await TUserLogin.findOne({
      where: {
        account_id: 'admin',
        login_client: 1
      }
    });

    if (existingLogin) {
      console.log('admin账号已存在，更新密码为123456');
      // 更新密码
      const hashedPassword = await bcrypt.hash('123456', 10);
      await existingLogin.update({
        account_pwd: hashedPassword,
        pwd_salt: null, // 新方式不需要盐
        updated_by: 1,
        updated_at: new Date()
      });
      console.log('admin账号密码更新成功');
      return;
    }

    // 使用bcrypt加密密码
    const hashedPassword = await bcrypt.hash('123456', 10);

    // 开始事务
    const transaction = await sequelize.transaction();

    try {
      // 创建用户
      const adminUser = await TUser.create({
        nick: '超级管理员',
        avatar: null,
        tag: 'admin',
        note: '系统超级管理员账号',
        role_type: 1, // 平台端
        user_status: 1, // 正常
        created_by: 1,
        updated_by: 1,
      }, { transaction });

      // 创建登录信息
      await TUserLogin.create({
        login_type: 1, // 账号名密码登录
        login_client: 1, // 平台端
        account_id: 'admin',
        account_pwd: hashedPassword,
        pwd_salt: null, // 新的bcrypt方式不需要salt
        user_id: adminUser.id,
        created_by: 1,
        updated_by: 1,
      }, { transaction });

      await transaction.commit();
      console.log('admin超管账号创建成功！');
      console.log('账号: admin');
      console.log('密码: 123456');
      console.log('用户ID:', adminUser.id);

    } catch (error) {
      await transaction.rollback();
      throw error;
    }

  } catch (error) {
    console.error('创建admin账号失败:', error.message);
  } finally {
    await sequelize.close();
  }
}

// 执行创建
createAdminAccount();